package com.neusoft.bizcore.activiti.converter;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.activiti.dto.LockDataDTO;
import com.neusoft.bizcore.activiti.model.LockData;
import com.neusoft.bizcore.activiti.repository.LockDataRepository;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.bizcore.web.utils.SpringUtil;

@Component
public class LockDataConverter extends AbstractConverter<LockData, LockDataDTO> {

    @Autowired
    private LockDataRepository lockDataRepository;

    @Override
    public LockData toModel(final LockDataDTO dto) {
        LockData model;

        if (dto.isNew()) {
            model = new LockData();
            model.setCreateTime(new Date());
        } else {
            model = this.lockDataRepository.getOne(dto.getId());
            model.setUpdateTime(new Date());
        }

        model.setServiceName(dto.getServiceName());
        model.setTableName(dto.getTableName());
        model.setDataId(dto.getDataId());
        model.setCode(dto.getCode());
        model.setWorkNum(dto.getWorkNum());
        model.setTaskId(dto.getTaskId());
        if (StringUtils.isNotEmpty(dto.getWorkNum())) {
            final String instanceId =
                    SpringUtil.getBean(WorkOrderService.class).getInstanceIdByWorkorderNum(dto.getWorkNum());
            model.setInstanceId(instanceId);
        }
        if (StringUtils.isNotEmpty(dto.getTaskId())) {
            final String nodeId = SpringUtil.getBean(ProcessInstanceService.class).getNodeIdByTaskId(dto.getTaskId());
            model.setNodeId(nodeId);
        }
        return model;
    }

    @Override
    public LockDataDTO toDTO(final LockData model, final boolean forListView) {

        final LockDataDTO dto = new LockDataDTO();

        dto.setId(model.getId());
        dto.setServiceName(model.getServiceName());
        dto.setTableName(model.getTableName());
        dto.setDataId(model.getDataId());
        dto.setCode(model.getCode());
        dto.setWorkNum(model.getWorkNum());
        dto.setTaskId(model.getTaskId());
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());

        return dto;
    }

}
